const Service = require("egg").Service;

class ProductService extends Service {
  // 查询商品列表
  async query(params) {
    const { app, ctx } = this;
    const Op = app.Sequelize.Op;
    const name = params.name || "";
    const where = {
      name: {
        [Op.like]: "%" + name + "%",
      },
      create_user_id: params.userId
    };
    let pageSize = +params.pageSize || 10;
    let currentPage = +params.currentPage || 1;
    const { count, rows } = await ctx.model.Product.findAndCountAll({
      order: [["updated_at", "DESC"]],
      limit: pageSize, // 每页多少条
      offset: pageSize * (currentPage - 1), // 跳过多少条
      where: where,
    });
    return {
      results: rows,
      total: count,
    };
  }
  // 新增商品
  async add(params) {
    const { ctx } = this;
    const { name, price, desc, userId } = params;
    const hasProduct = await ctx.model.findOne({
      where:{
        name
      }
    })
    if(hasProduct){
      throw '产品已存在'
    }
    const product = new ctx.model.Product();
    product.name = name;
    product.price = price;
    product.desc = desc;
    product.create_user_id = userId;
    await product.save();
    return "添加成功";
  }
  // 更新商品信息
  async update(id, params) {
    const { ctx } = this;
    const product = await ctx.model.Product.update(
      { ...params },
      {
        where: {
          id,
        },
      }
    );
    return "更新成功";
  }
  // 查询商品详情
  async detail(id) {
    const { ctx } = this;
    const product = await ctx.model.Product.findOne({
      where: {
        id,
      },
    });
    return product;
  }
  // 删除商品
  async delete(id) {
    const { ctx } = this;
    const hasProduct = await ctx.model.Product.findOne({
      where: {
        id,
      },
    });
    if (!hasProduct) {
      throw "未找到要删除的商品";
    }
    const result = await ctx.model.Product.destroy({
      where: {
        id,
      },
    });
    if (result === 1) {
      return "删除成功";
    } else {
      throw '删除失败'
    }
  }
}
module.exports = ProductService;
